<template>
  <div class="barcode-scanner-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>商品扫码识别</h3>
          <div class="header-actions">
            <el-button type="primary" @click="startScan" :disabled="isScanning">
              <el-icon><Camera /></el-icon>
              {{ isScanning ? '扫描中...' : '开始扫描' }}
            </el-button>
            <el-button type="success" @click="showManualInput">
              <el-icon><Edit /></el-icon>
              手动输入
            </el-button>
            <el-button type="warning" @click="showHistory">
              <el-icon><Clock /></el-icon>
              扫描历史
            </el-button>
          </div>
        </div>
      </template>

      <!-- 扫码区域 -->
      <div class="scanner-container">
        <div class="scanner-area">
          <div v-if="!isScanning" class="scanner-placeholder">
            <el-icon size="64"><Camera /></el-icon>
            <h3>商品扫码识别</h3>
            <p>点击"开始扫描"按钮启动摄像头进行商品条码扫描</p>
            <div class="scanner-tips">
              <h4>扫描提示：</h4>
              <ul>
                <li>确保条码清晰可见</li>
                <li>保持适当的距离（10-30cm）</li>
                <li>避免强光直射</li>
                <li>支持EAN-13、UPC-A、Code128等格式</li>
              </ul>
            </div>
          </div>
          
          <div v-else class="scanner-active">
            <div class="camera-container">
              <video ref="videoRef" autoplay playsinline></video>
              <canvas ref="canvasRef" style="display: none;"></canvas>
              <div class="scan-overlay">
                <div class="scan-frame"></div>
                <div class="scan-line"></div>
              </div>
            </div>
            <div class="scan-controls">
              <el-button type="danger" @click="stopScan">停止扫描</el-button>
              <el-button type="info" @click="toggleFlash" :disabled="!hasFlash">
                <el-icon><Flash /></el-icon>
                {{ flashOn ? '关闭闪光灯' : '开启闪光灯' }}
              </el-button>
            </div>
          </div>
        </div>

        <!-- 扫描结果 -->
        <div v-if="scanResult" class="scan-result">
          <el-card>
            <template #header>
              <div class="result-header">
                <span>扫描结果</span>
                <el-tag :type="scanResult.success ? 'success' : 'danger'">
                  {{ scanResult.success ? '识别成功' : '识别失败' }}
                </el-tag>
              </div>
            </template>
            
            <div v-if="scanResult.success" class="product-info">
              <div class="product-image">
                <el-image :src="scanResult.product.image" fit="cover" />
              </div>
              <div class="product-details">
                <h4>{{ scanResult.product.name }}</h4>
                <p><strong>商品编码:</strong> {{ scanResult.product.code }}</p>
                <p><strong>条码:</strong> {{ scanResult.barcode }}</p>
                <p><strong>分类:</strong> {{ scanResult.product.category }}</p>
                <p><strong>价格:</strong> <span class="price">¥{{ scanResult.product.salePrice.toFixed(2) }}</span></p>
                <p><strong>库存:</strong> {{ scanResult.product.stock }}件</p>
                <p><strong>规格:</strong> {{ scanResult.product.specification }}</p>
              </div>
              <div class="product-actions">
                <el-button type="primary" @click="addToCart(scanResult.product)">
                  <el-icon><Plus /></el-icon>
                  加入购物车
                </el-button>
                <el-button type="success" @click="viewProductDetails(scanResult.product)">
                  <el-icon><View /></el-icon>
                  查看详情
                </el-button>
              </div>
            </div>
            
            <div v-else class="scan-error">
              <el-icon size="48" color="#f56c6c"><Warning /></el-icon>
              <h4>条码识别失败</h4>
              <p>条码: {{ scanResult.barcode }}</p>
              <p>可能的原因：</p>
              <ul>
                <li>条码不清晰或损坏</li>
                <li>商品未在系统中注册</li>
                <li>条码格式不支持</li>
              </ul>
              <div class="error-actions">
                <el-button type="primary" @click="retryScan">重新扫描</el-button>
                <el-button type="success" @click="addNewProduct(scanResult.barcode)">添加新商品</el-button>
              </div>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 手动输入对话框 -->
      <el-dialog
        v-model="manualInputVisible"
        title="手动输入条码"
        width="500px"
      >
        <el-form :model="manualForm" :rules="manualRules" ref="manualFormRef" label-width="100px">
          <el-form-item label="条码" prop="barcode">
            <el-input 
              v-model="manualForm.barcode" 
              placeholder="请输入商品条码"
              @keyup.enter="searchByBarcode"
            />
          </el-form-item>
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="manualForm.name" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="商品编码" prop="code">
            <el-input v-model="manualForm.code" placeholder="请输入商品编码" />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <el-button @click="manualInputVisible = false">取消</el-button>
          <el-button type="primary" @click="searchByBarcode" :loading="searchLoading">
            查询商品
          </el-button>
        </template>
      </el-dialog>

      <!-- 扫描历史对话框 -->
      <el-dialog
        v-model="historyVisible"
        title="扫描历史"
        width="800px"
      >
        <div class="history-content">
          <div class="history-filters">
            <el-form inline>
              <el-form-item label="时间范围">
                <el-date-picker
                  v-model="historyFilters.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="historyFilters.status" placeholder="选择状态" clearable>
                  <el-option label="成功" value="success" />
                  <el-option label="失败" value="failed" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="loadHistory">查询</el-button>
                <el-button @click="clearHistory">清空历史</el-button>
              </el-form-item>
            </el-form>
          </div>
          
          <el-table :data="scanHistory" border stripe>
            <el-table-column prop="time" label="扫描时间" width="180" />
            <el-table-column prop="barcode" label="条码" width="150" />
            <el-table-column prop="productName" label="商品名称" width="200" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'success' ? 'success' : 'danger'">
                  {{ row.status === 'success' ? '成功' : '失败' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="operator" label="操作员" width="120" />
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="rescanItem(row)">
                  重新扫描
                </el-button>
                <el-button type="danger" size="small" @click="deleteHistoryItem(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-dialog>

      <!-- 添加新商品对话框 -->
      <el-dialog
        v-model="addProductVisible"
        title="添加新商品"
        width="600px"
      >
        <el-form :model="newProductForm" :rules="newProductRules" ref="newProductFormRef" label-width="100px">
          <el-form-item label="条码" prop="barcode">
            <el-input v-model="newProductForm.barcode" readonly />
          </el-form-item>
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="newProductForm.name" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="商品编码" prop="code">
            <el-input v-model="newProductForm.code" placeholder="请输入商品编码" />
          </el-form-item>
          <el-form-item label="分类" prop="category">
            <el-select v-model="newProductForm.category" placeholder="选择分类" style="width: 100%">
              <el-option label="电子产品" value="电子产品" />
              <el-option label="服装鞋帽" value="服装鞋帽" />
              <el-option label="食品饮料" value="食品饮料" />
              <el-option label="日用品" value="日用品" />
            </el-select>
          </el-form-item>
          <el-form-item label="规格" prop="specification">
            <el-input v-model="newProductForm.specification" placeholder="请输入规格" />
          </el-form-item>
          <el-form-item label="单位" prop="unit">
            <el-input v-model="newProductForm.unit" placeholder="请输入单位" />
          </el-form-item>
          <el-form-item label="采购价" prop="purchasePrice">
            <el-input-number v-model="newProductForm.purchasePrice" :min="0" :precision="2" style="width: 100%" />
          </el-form-item>
          <el-form-item label="销售价" prop="salePrice">
            <el-input-number v-model="newProductForm.salePrice" :min="0" :precision="2" style="width: 100%" />
          </el-form-item>
          <el-form-item label="库存" prop="stock">
            <el-input-number v-model="newProductForm.stock" :min="0" style="width: 100%" />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <el-button @click="addProductVisible = false">取消</el-button>
          <el-button type="primary" @click="saveNewProduct" :loading="saveLoading">
            保存商品
          </el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const isScanning = ref(false)
const hasFlash = ref(false)
const flashOn = ref(false)
const scanResult = ref(null)
const manualInputVisible = ref(false)
const historyVisible = ref(false)
const addProductVisible = ref(false)
const searchLoading = ref(false)
const saveLoading = ref(false)

// 表单引用
const manualFormRef = ref()
const newProductFormRef = ref()

// 摄像头相关
const videoRef = ref()
const canvasRef = ref()
let stream = null
let scanInterval = null

// 手动输入表单
const manualForm = reactive({
  barcode: '',
  name: '',
  code: ''
})

// 新商品表单
const newProductForm = reactive({
  barcode: '',
  name: '',
  code: '',
  category: '',
  specification: '',
  unit: '',
  purchasePrice: 0,
  salePrice: 0,
  stock: 0
})

// 历史记录筛选
const historyFilters = reactive({
  dateRange: [],
  status: ''
})

// 扫描历史
const scanHistory = ref([
  {
    id: 1,
    time: '2024-01-15 14:30:25',
    barcode: '6901234567890',
    productName: '可口可乐',
    status: 'success',
    operator: '收银员001'
  },
  {
    id: 2,
    time: '2024-01-15 14:28:15',
    barcode: '6901234567891',
    productName: '未识别商品',
    status: 'failed',
    operator: '收银员001'
  }
])

// 表单验证规则
const manualRules = {
  barcode: [
    { required: true, message: '请输入条码', trigger: 'blur' }
  ]
}

const newProductRules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入商品编码', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  salePrice: [
    { required: true, message: '请输入销售价', trigger: 'blur' }
  ]
}

// 模拟商品数据库
const productDatabase = {
  '6901234567890': {
    id: 1,
    code: 'P001',
    name: '可口可乐',
    category: '食品饮料',
    specification: '330ml',
    unit: '瓶',
    purchasePrice: 2.5,
    salePrice: 3.5,
    stock: 100,
    image: 'https://via.placeholder.com/150x150/409EFF/FFFFFF?text=CocaCola'
  },
  '6901234567891': {
    id: 2,
    code: 'P002',
    name: '洗发水',
    category: '日用品',
    specification: '500ml',
    unit: '瓶',
    purchasePrice: 25.0,
    salePrice: 35.0,
    stock: 50,
    image: 'https://via.placeholder.com/150x150/67C23A/FFFFFF?text=Shampoo'
  }
}

// 方法
const startScan = async () => {
  try {
    // 请求摄像头权限
    stream = await navigator.mediaDevices.getUserMedia({ 
      video: { 
        facingMode: 'environment', // 使用后置摄像头
        width: { ideal: 1280 },
        height: { ideal: 720 }
      } 
    })
    
    videoRef.value.srcObject = stream
    isScanning.value = true
    hasFlash.value = stream.getVideoTracks()[0].getCapabilities().torch || false
    
    // 开始扫描检测
    startScanDetection()
    
    ElMessage.success('摄像头启动成功')
  } catch (error) {
    console.error('摄像头启动失败:', error)
    ElMessage.error('摄像头启动失败，请检查权限设置')
  }
}

const stopScan = () => {
  if (stream) {
    stream.getTracks().forEach(track => track.stop())
    stream = null
  }
  
  if (scanInterval) {
    clearInterval(scanInterval)
    scanInterval = null
  }
  
  isScanning.value = false
  flashOn.value = false
  ElMessage.info('扫描已停止')
}

const startScanDetection = () => {
  scanInterval = setInterval(() => {
    if (videoRef.value && canvasRef.value) {
      const canvas = canvasRef.value
      const video = videoRef.value
      const context = canvas.getContext('2d')
      
      canvas.width = video.videoWidth
      canvas.height = video.videoHeight
      context.drawImage(video, 0, 0, canvas.width, canvas.height)
      
      // 这里应该集成实际的条码识别库
      // 模拟条码识别
      if (Math.random() > 0.95) { // 5%的概率识别到条码
        const mockBarcode = '6901234567890'
        processScanResult(mockBarcode)
      }
    }
  }, 100)
}

const processScanResult = (barcode) => {
  stopScan()
  
  const product = productDatabase[barcode]
  
  scanResult.value = {
    success: !!product,
    barcode: barcode,
    product: product || null,
    timestamp: new Date().toLocaleString()
  }
  
  // 添加到扫描历史
  addToHistory(barcode, product?.name || '未识别商品', !!product)
  
  if (product) {
    ElMessage.success(`商品识别成功: ${product.name}`)
  } else {
    ElMessage.warning('商品未找到，请手动添加')
  }
}

const addToHistory = (barcode, productName, success) => {
  const historyItem = {
    id: Date.now(),
    time: new Date().toLocaleString(),
    barcode: barcode,
    productName: productName,
    status: success ? 'success' : 'failed',
    operator: '当前用户'
  }
  
  scanHistory.value.unshift(historyItem)
  
  // 保存到本地存储
  localStorage.setItem('scanHistory', JSON.stringify(scanHistory.value))
}

const toggleFlash = () => {
  if (stream && hasFlash.value) {
    const track = stream.getVideoTracks()[0]
    track.applyConstraints({
      advanced: [{ torch: !flashOn.value }]
    }).then(() => {
      flashOn.value = !flashOn.value
    }).catch(error => {
      console.error('闪光灯切换失败:', error)
    })
  }
}

const showManualInput = () => {
  manualInputVisible.value = true
  Object.assign(manualForm, {
    barcode: '',
    name: '',
    code: ''
  })
}

const searchByBarcode = async () => {
  if (!manualForm.barcode) {
    ElMessage.warning('请输入条码')
    return
  }
  
  searchLoading.value = true
  
  // 模拟搜索延迟
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  const product = productDatabase[manualForm.barcode]
  
  if (product) {
    scanResult.value = {
      success: true,
      barcode: manualForm.barcode,
      product: product,
      timestamp: new Date().toLocaleString()
    }
    addToHistory(manualForm.barcode, product.name, true)
    ElMessage.success('商品查询成功')
    manualInputVisible.value = false
  } else {
    ElMessage.warning('未找到该条码对应的商品')
  }
  
  searchLoading.value = false
}

const showHistory = () => {
  historyVisible.value = true
  loadHistory()
}

const loadHistory = () => {
  // 从本地存储加载历史记录
  const saved = localStorage.getItem('scanHistory')
  if (saved) {
    scanHistory.value = JSON.parse(saved)
  }
}

const clearHistory = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有扫描历史吗？',
      '确认清空',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    scanHistory.value = []
    localStorage.removeItem('scanHistory')
    ElMessage.success('历史记录已清空')
  } catch {
    // 用户取消操作
  }
}

const rescanItem = (item) => {
  manualForm.barcode = item.barcode
  showManualInput()
  historyVisible.value = false
}

const deleteHistoryItem = async (item) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条记录吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = scanHistory.value.findIndex(h => h.id === item.id)
    if (index > -1) {
      scanHistory.value.splice(index, 1)
      localStorage.setItem('scanHistory', JSON.stringify(scanHistory.value))
      ElMessage.success('记录已删除')
    }
  } catch {
    // 用户取消操作
  }
}

const addToCart = (product) => {
  ElMessage.success(`已添加 ${product.name} 到购物车`)
  // 这里可以触发父组件的添加购物车事件
}

const viewProductDetails = (product) => {
  ElMessage.info(`查看商品详情: ${product.name}`)
}

const retryScan = () => {
  scanResult.value = null
  startScan()
}

const addNewProduct = (barcode) => {
  newProductForm.barcode = barcode
  addProductVisible.value = true
  scanResult.value = null
}

const saveNewProduct = async () => {
  if (!newProductFormRef.value) return
  
  try {
    await newProductFormRef.value.validate()
    saveLoading.value = true
    
    // 模拟保存过程
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 添加到商品数据库
    const newProduct = {
      id: Date.now(),
      ...newProductForm,
      image: 'https://via.placeholder.com/150x150/909399/FFFFFF?text=New'
    }
    
    productDatabase[newProductForm.barcode] = newProduct
    
    ElMessage.success('商品添加成功')
    addProductVisible.value = false
    
    // 显示新添加的商品
    scanResult.value = {
      success: true,
      barcode: newProduct.barcode,
      product: newProduct,
      timestamp: new Date().toLocaleString()
    }
    
    addToHistory(newProduct.barcode, newProduct.name, true)
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    saveLoading.value = false
  }
}

// 生命周期
onMounted(() => {
  loadHistory()
})

onUnmounted(() => {
  stopScan()
})
</script>

<style scoped>
.barcode-scanner-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.scanner-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.scanner-area {
  min-height: 400px;
  border: 2px dashed #e4e7ed;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
}

.scanner-placeholder {
  text-align: center;
  color: #909399;
  padding: 40px;
}

.scanner-placeholder h3 {
  margin: 16px 0;
  color: #606266;
}

.scanner-placeholder p {
  margin: 0 0 24px 0;
  font-size: 14px;
}

.scanner-tips {
  text-align: left;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.scanner-tips h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 14px;
}

.scanner-tips ul {
  margin: 0;
  padding-left: 20px;
}

.scanner-tips li {
  margin-bottom: 8px;
  font-size: 13px;
  color: #606266;
}

.scanner-active {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.camera-container {
  position: relative;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
}

.camera-container video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.scan-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.scan-frame {
  width: 250px;
  height: 150px;
  border: 2px solid #409eff;
  border-radius: 8px;
  position: relative;
}

.scan-line {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, transparent, #409eff, transparent);
  animation: scan 2s linear infinite;
}

@keyframes scan {
  0% { transform: translateY(0); }
  100% { transform: translateY(148px); }
}

.scan-controls {
  padding: 16px;
  text-align: center;
  background: white;
  border-top: 1px solid #e4e7ed;
}

.scan-result {
  margin-top: 20px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-info {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.product-image {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
}

.product-details {
  flex: 1;
}

.product-details h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 18px;
}

.product-details p {
  margin: 8px 0;
  color: #606266;
  font-size: 14px;
}

.price {
  color: #f56c6c;
  font-weight: 600;
  font-size: 16px;
}

.product-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex-shrink: 0;
}

.scan-error {
  text-align: center;
  padding: 40px;
}

.scan-error h4 {
  margin: 16px 0;
  color: #f56c6c;
}

.scan-error p {
  margin: 8px 0;
  color: #606266;
}

.scan-error ul {
  text-align: left;
  margin: 16px 0;
  padding-left: 20px;
}

.scan-error li {
  margin-bottom: 8px;
  color: #909399;
  font-size: 14px;
}

.error-actions {
  margin-top: 24px;
  display: flex;
  gap: 12px;
  justify-content: center;
}

.history-content {
  padding: 20px 0;
}

.history-filters {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .scanner-area {
    min-height: 300px;
  }
  
  .scan-frame {
    width: 200px;
    height: 120px;
  }
  
  .product-info {
    flex-direction: column;
    text-align: center;
  }
  
  .product-actions {
    flex-direction: row;
    justify-content: center;
  }
  
  .error-actions {
    flex-direction: column;
  }
  
  .history-filters .el-form {
    flex-direction: column;
  }
  
  .history-filters .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
}
</style>
